/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.yczbj.ycvideoplayer.ability;

import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.bundle.AbilityInfo;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import com.yc.video.bridge.ControlWrapper;
import com.yc.video.config.ConstantKeys;
import com.yc.video.player.SimpleStateListener;
import com.yc.video.player.VideoPlayer;
import com.yc.video.tool.BaseToast;
import com.yc.video.ui.view.BasisVideoController;
import com.yc.videocache.HttpProxyCacheServer;
import com.yc.videocache.cache.ProxyVideoCacheManager;

import org.yczbj.ycvideoplayer.ConstantVideo;
import org.yczbj.ycvideoplayer.ResourceTable;
import org.yczbj.ycvideoplayer.ability.ad.AdControlView;
import org.yczbj.ycvideoplayer.utils.ImageLoader;

/**
 * 8.1 播放器添加自定义广告
 *
 * @since 2021-05-10
 */
public class AdAbility extends BaseAbility implements Component.ClickedListener {
    private static final String URL_AD = "https://gslb.miaopai.com/stream/IR3oMYDhrON5huCmf7sHCfnU5YKEkgO2.mp4";
    private VideoPlayer mVideoPlayer;
    private Button mBtnScaleNormal;
    private Button mBtnScale169;
    private Button mBtnScale43;
    private Button mBtnCrop;
    private Button mBtnGif;
    private AdControlView adControlView;

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_ability_ad_video;
    }

    @Override
    protected void initComponent(Intent intent) {
        super.initComponent(intent);
        mVideoPlayer = (VideoPlayer) findComponentById(ResourceTable.Id_video_player);
        mBtnScaleNormal = (Button) findComponentById(ResourceTable.Id_btn_scale_normal);
        mBtnScale169 = (Button) findComponentById(ResourceTable.Id_btn_scale_169);
        mBtnScale43 = (Button) findComponentById(ResourceTable.Id_btn_scale_43);
        mBtnCrop = (Button) findComponentById(ResourceTable.Id_btn_crop);
        mBtnGif = (Button) findComponentById(ResourceTable.Id_btn_gif);
        initVideoPlayer();
    }

    private void initVideoPlayer() {
        mController = new BasisVideoController(this);
        mController.setGestureEnabled(false);
        adControlView = new AdControlView(this);
        adControlView.setListener(new AdControlView.AdControlListener() {
            @Override
            public void onAdClick() {
                BaseToast.showRoundRectToast("广告点击跳转");
            }

            @Override
            public void onSkipAd() {
                runMainThread(new Runnable() {
                    @Override
                    public void run() {
                        playVideo();
                    }
                });
            }
        });
        mController.addControlComponent(adControlView);

        // 设置视频背景图
        ImageLoader.loadImage(getContext(), ResourceTable.Media_image_default, mController.getThumb());

        // 设置控制器
        mVideoPlayer.setController(mController);
        HttpProxyCacheServer cacheServer = ProxyVideoCacheManager.getProxy(this);
        String proxyUrl = cacheServer.getProxyUrl(URL_AD);

        mVideoPlayer.setUrl(proxyUrl);
        mVideoPlayer.start();

        // 监听播放结束
        mVideoPlayer.addOnStateChangeListener(new SimpleStateListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                if (playState == ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING) {
                    runMainThread(new Runnable() {
                        @Override
                        public void run() {
                            playVideo();
                        }
                    });
                }
            }
        });
    }

    /**
     * 播放正片
     */
    private void playVideo() {
        mVideoPlayer.release();
        mController.removeAllControlComponent();
        mController.setSensorManager();
        mController.addDefaultControlComponent("正片");
        mController.setGestureEnabled(true);

        // 重新设置数据
        mVideoPlayer.setUrl(ConstantVideo.VideoPlayerList.get(0));

        // 开始播放
        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
            @Override
            public void run() {
                mVideoPlayer.start();
            }
        }, 50);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mBtnScaleNormal.setClickedListener(this);
        mBtnScale169.setClickedListener(this);
        mBtnScale43.setClickedListener(this);
        mBtnCrop.setClickedListener(this);
        mBtnGif.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {
        if (component == mBtnScale169) {
            mVideoPlayer.setScreenScaleType(ConstantKeys.PlayerScreenScaleType.SCREEN_SCALE_16_9);
        } else if (component == mBtnScaleNormal) {
            mVideoPlayer.setScreenScaleType(ConstantKeys.PlayerScreenScaleType.SCREEN_SCALE_DEFAULT);
        } else if (component == mBtnScale43) {
            mVideoPlayer.setScreenScaleType(ConstantKeys.PlayerScreenScaleType.SCREEN_SCALE_4_3);
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
        if (mVideoPlayer != null) {
            mVideoPlayer.resume();
        }
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if (mVideoPlayer != null) {
            mVideoPlayer.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mVideoPlayer != null) {
            mVideoPlayer.release();
        }
    }

    @Override
    protected void onBackPressed() {
        ControlWrapper.defaultValue();
        if (mVideoPlayer == null || !mVideoPlayer.onBackPressed()) {
            super.onBackPressed();
        }
    }

    /**
     * 切换任务到主线程执行
     *
     * @param runnable 执行的runnable
     */
    public static void runMainThread(Runnable runnable) {
        EventRunner eventRunner = EventRunner.getMainEventRunner();
        EventHandler eventHandler = new EventHandler(eventRunner);
        eventHandler.postTask(runnable);
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
        if (adControlView != null) {
            if (displayOrientation.equals(AbilityInfo.DisplayOrientation.PORTRAIT)) {
                adControlView.onPlayerStateChanged(ConstantKeys.PlayMode.MODE_NORMAL);
            } else if (displayOrientation.equals(AbilityInfo.DisplayOrientation.LANDSCAPE)) {
                adControlView.onPlayerStateChanged(ConstantKeys.PlayMode.MODE_FULL_SCREEN);
            }
        }
    }
}
